import br.com.nooclix.salon.ui.dto.attendance.AttendanceSheetBusyTO;
import br.com.nooclix.salon.ui.dto.attendance.AttendanceSheetTO;
import br.com.nooclix.salon.ui.dto.attendance.AttendanceTO;
import br.com.nooclix.salon.ui.dto.customer.CustomerTO;
import br.com.nooclix.salon.ui.dto.product.ProductTO;
import br.com.nooclix.salon.ui.dto.service.ServiceTO;
import br.com.nooclix.salon.ui.screen.attendancesheet.AttendanceSheetWindow;
import br.com.nooclix.salon.ui.screen.attendancesheet.chooses.ChooseAttendance;
import br.com.nooclix.salon.ui.screen.customer.CustomerWindow;
import br.com.nooclix.salon.ui.util.Utilitys;
import br.com.nooclix.salon.ui.util.WindowsMessage;

import flash.events.Event;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.core.mx_internal;
import mx.events.CloseEvent;
import mx.events.DropdownEvent;
import mx.managers.PopUpManager;

protected var attendanceSheet:AttendanceSheetTO;

protected var chooseAttendance:ChooseAttendance;

protected var attendanceSelected:AttendanceTO;

private var numProduct:int = 0;

private var numService:int = 0;

private var windowType:int = 0;

private var reduceProduct:Boolean = false;

private var reduceService:Boolean = false;

private var customerWindow:CustomerWindow;

private var windowState:String;

protected var listStatus:ArrayCollection = new ArrayCollection();

protected var bookingByStatusList:ArrayCollection;

protected var listBusyEmployee:ArrayCollection;

protected var busyAttendanceSheet:AttendanceSheetBusyTO;

protected var attendance:ArrayCollection;


public function start():void{
	
	var hours:ArrayCollection = new ArrayCollection();
	
	for(var i:int = 0; i < 24;i++){
		
		if(i.toString().length == 1){
			hours.addItem("0" + i.toString());
		}else{
			hours.addItem(i.toString());
		}
	}
	
	cbHour.dataProvider = hours;
	
	var mins:ArrayCollection = new ArrayCollection();
	mins.addItem("00");
	for(var y:int = 1; y < 6;y++){
		
		mins.addItem((10 * y).toString());
		
	}
	cbMinute.dataProvider = mins;
	
	getCbStatus();
}
private function newCustomer():void{
	windowState = this.currentState;
	this.currentState = "newCustomer";
}
private function saveCustomer():void{
	var customer:CustomerTO = new CustomerTO();
	customer.person = personView.getPerson();
	
	customerRemote.persist(customer);
	
	personView.clearFields();
}
private function backAttendance():void{
	this.currentState = windowState;
	findCustomerByName();
}
private function saveAttendanceReserved():void{
	//Alert.show("Attendances: "+attendanceSheet.attendance.length.toString());
	//attendanceSheet = new AttendanceSheetTO();
	attendanceSheet.customer = cbCustomer.selectedItem as CustomerTO;
	//Alert.show("Customer selected: "+attendanceSheet.customer.person.name);
	attendanceSheet.status = fieldStatus.text;
	//attendanceSheet.total = fieldReserve.text as Number;
	attendanceSheet.date = new Date(dateField.selectedDate.fullYear, dateField.selectedDate.month, dateField.selectedDate.date, null, null, null, null)
	attendanceSheet.hour = new Date(null, null, null, cbHour.text, cbMinute.text, 0);
	attendanceSheetRemote.persist(attendanceSheet);
	clearFields();
}

private function saveAttendanceInicialized():void{
	//Alert.show("Attendances: "+attendanceSheet.attendance.length.toString());
	//attendanceSheet = new AttendanceSheetTO();
	attendanceSheet.customer = cbCustomer.selectedItem as CustomerTO;
	//Alert.show("Customer selected: "+attendanceSheet.customer.person.name);
	if(attendanceSheet.status == "Reserva"){
		attendanceSheet.status = "Iniciado";
		alterAttendanceSheetRemote.alterAttendanceSheet(attendanceSheet);
		return;
	}else{
		attendanceSheet.status = fieldStatusView.text;
	}
	//attendanceSheet.total = fieldReserve.text as Number;
	attendanceSheet.date = new Date(dateField.selectedDate.fullYear, dateField.selectedDate.month, dateField.selectedDate.date, null, null, null, null)
	attendanceSheet.hour = new Date(null, null, null, cbHour.text, cbMinute.text, 0);
	attendanceSheetRemote.persist(attendanceSheet);
	clearFields();
}
private function removeItemAttendance():void{
	if(gridAttendances.selectedItem == null){
		WindowsMessage.alarmWithTitle("Ops, selecione um serviÃ§o/produto para poder excluir.","ExclusÃ£o");
		return;
	}
	
	var a:AttendanceTO = gridAttendances.selectedItem as AttendanceTO; 
	WindowsMessage.question("Deseja excluir o serviÃ§o/produto?","DeleÃ§Ã£o",function (event:CloseEvent):void{
		if(event.detail == Alert.YES){
			removeItemSelected(a);
			if(a.product != null){
				reduceProduct = true;
				calcTotal();
				reduceProduct = false;
			}
			if(a.service !=null){
				reduceService = true;
				calcTotal();
				reduceService = false;
			}
			calcTotal();
			
		}
	});
}
private function alterAttendanceSheet():void{
	numProduct =1;
	numService =1;
	attendanceSelected = null;
	attendanceSheet = null;
	attendanceSheet = gridAttendanceSheet.selectedItem as AttendanceSheetTO;
	gridAttendances.dataProvider = attendanceSheet.attendance;
	dateField.selectedDate = attendanceSheet.date;
	if(attendanceSheet.hour.hours.toString().length == 1){
		Utilitys.selectItem("0"+attendanceSheet.hour.hours.toString(),cbHour,null);
	}
	Utilitys.selectItem(attendanceSheet.hour.hours.toString(),cbHour,null);
	Utilitys.selectItem(attendanceSheet.hour.minutes.toString(),cbMinute,null);
	calcTotal();
	if(attendanceSheet.status != "Cancelado"){
		if(attendanceSheet.status == "Iniciado"){
			this.currentState = "alterBookingView";
		}else if(attendanceSheet.status == "Reserva"){
			this.currentState = "alterBookingViewReserve";
		}else if(attendanceSheet.status == "Finalizado"){
			this.currentState = "alterFinalized";
		}
	}else{
		WindowsMessage.alarm("NÃ£o Ã© possÃ­vel alterar um atendimento apÃ³s ter sido Cancelado!");
	}
}
private function saveAlterAttendanceSheet():void{
	attendanceSheet.customer = cbCustomer.selectedItem as CustomerTO;
	if(attendanceSheet.status != "Reserva"){
		attendanceSheet.status = fieldStatusView.text;
	}else{
		attendanceSheet.status = fieldStatus.text;
	}
	attendanceSheet.date = new Date(dateField.selectedDate.fullYear, dateField.selectedDate.month, dateField.selectedDate.date, null, null, null, null)
	attendanceSheet.hour = new Date(null, null, null, cbHour.text, cbMinute.text, 0);
	alterAttendanceSheetRemote.alterAttendanceSheet(attendanceSheet);
}

private function removeItemSelected(a:AttendanceTO):void{
	attendanceSheet.removeItem(a);
	gridAttendances.dataProvider = attendanceSheet.attendance;
}
private function removeAttendanceSheetSelected():void{
	if(gridAttendanceSheet.selectedItem == null){
		WindowsMessage.alarmWithTitle("Ops, selecione um atendimento para excluir.","ExclusÃ£o");
		return;
	}
	var att:AttendanceSheetTO = gridAttendanceSheet.selectedItem as AttendanceSheetTO;
	if(att.status != "Finalizado" && att.status != "Cancelado" && att.status != "Iniciado"){
		
		WindowsMessage.question("Deseja excluir o atendimento? ","DeleÃ§Ã£o",function (event:CloseEvent):void{
			if(event.detail == Alert.YES){
				attendanceSheetRemote.removeAttendanceSheet(att);
				findBookingByStatusController();
			}
		});
	}else{
		WindowsMessage.alarm("Ops, este atendimento nÃ£o pode ser excluÃ­do por estar "+att.status);
	}
	
}

private function cbCustomerLabelFunction(item:Object):String {
	var c:CustomerTO = item as CustomerTO;
	return c.person.name;
}

protected function openChooseService():void{
	chooseAttendance = new ChooseAttendance();
	PopUpManager.addPopUp(chooseAttendance, this, true);
	chooseAttendance.currentState = "service";
	PopUpManager.centerPopUp(chooseAttendance);
	windowType = 1;
	chooseAttendance.addEventListener("ClosePopUpAttendance", loadAttendance);
}
protected function openChooseProduct():void{
	chooseAttendance = new ChooseAttendance();
	PopUpManager.addPopUp(chooseAttendance, this , true);
	chooseAttendance.currentState = "product";
	PopUpManager.centerPopUp(chooseAttendance);
	windowType = 0;
	chooseAttendance.addEventListener("ClosePopUpAttendance", loadAttendance);
}
public function loadAttendance(event:Event):void{
	attendanceSelected = null;
	
	attendanceSelected = chooseAttendance.getAttendanceSelected();
	if(attendanceSheet == null){
		attendanceSheet = new AttendanceSheetTO();
	}
	
	if(windowType == 0){
		verifyProductEquals(attendanceSelected);
		gridAttendances.dataProvider = attendanceSheet.attendance;
	}else if(windowType == 1){
		verifyServiceEquals(attendanceSelected);
		gridAttendances.dataProvider = attendanceSheet.attendance;
	}
}
public function calcTotal():void{
	var totalProduct:Number = 0.0;
	var totalService:Number = 0.0;
	var totalAttendanceSheet:Number = 0.0;
	
	for each(var att:AttendanceTO in attendanceSheet.attendance){
		if(att.product !=null || reduceProduct == true){
			totalProduct = totalProduct + att.total;
			fieldTotalProducts.text = Utilitys.formatCurrencyBR(totalProduct).toString();
		}
		if(att.service != null || reduceService == true){
			totalService = totalService + att.total;
			fieldTotalServices.text = Utilitys.formatCurrencyBR(totalService).toString();
			
		}
		if(reduceService == true && att.service == null){
			fieldTotalServices.text = Utilitys.formatCurrencyBR(0.0).toString();
		}
		if(reduceProduct == true && att.product == null){
			fieldTotalProducts.text = Utilitys.formatCurrencyBR(0.00).toString();
		}
	}
	totalAttendanceSheet = totalProduct + totalService;
	
	if(totalAttendanceSheet == 0.0){
		fieldTotalProducts.text = Utilitys.formatCurrencyBR(0.0).toString();
		fieldTotalServices.text = Utilitys.formatCurrencyBR(0.0).toString();
	}
	
	fieldReserve.text = Utilitys.formatCurrencyBR(totalAttendanceSheet).toString();
	attendanceSheet.total = totalAttendanceSheet;
}

private function verifyServiceEquals(attSelected:AttendanceTO):void{
	
	if(numService == 0){
		attendanceSheet.addItem(attSelected);
		calcTotal();
		numService = 1;
	}else{
		for each(var att:AttendanceTO in attendanceSheet.attendance){
			if(att.service != null){
				if(att.service.name == attSelected.service.name){
					WindowsMessage.alarm("O serviÃ§o jÃ¡ foi adicionado!");
					return;
				}
			}
		}
		attendanceSheet.addItem(attSelected);
		calcTotal();
		
	}
}
private function verifyProductEquals(attSelected:AttendanceTO):void{
	if(numProduct == 0){
		attendanceSheet.addItem(attSelected);
		calcTotal();
		numProduct =1;
	}else{
		
		for each(var att:AttendanceTO in attendanceSheet.attendance){
			if(att.product != null){
				if(att.product.name == attSelected.product.name){
					WindowsMessage.alarm("O produto jÃ¡ foi adicionado!");
					return;
				}
			}	
		}
		
		attendanceSheet.addItem(attSelected);
		calcTotal();
	}
}
private function clearFields():void{
	fieldCustomerSearch.text = " ";
	fieldReserve.text = "0.00";
	fieldTotalProducts.text = "0.00";
	fieldTotalServices.text = "0.00";
	cbHour.text = "00";
	cbMinute.text = "00";
	gridAttendances.dataProvider = null;
	attendanceSheet = null;
	
}
private function findCustomerByName():void{
	customerRemote.findByName(fieldCustomerSearch.text);
}
private function findBookingByStatusController():void{
	bookingByStatusList = new ArrayCollection();
	if(dtStart.selectedDate == null || dtEnd.selectedDate == null){
		WindowsMessage.alarm("Infome o perÃ­odo inicial e final para efetuar a pesquisa!");
		return;
	}
	attendanceSheetRemote.findBookingByStatusController(cbCustomer.selectedItem,
		dtStart.selectedDate, dtEnd.selectedDate, cbStatus.selectedItem);
	
	gridAttendanceDetail.dataProvider = null;
}
private function showAttendancesDetail():void{
	gridAttendanceDetail.dataProvider = gridAttendanceSheet.selectedItem.attendance;
}

private function finalizeAttendance():void{
	var attSheet:AttendanceSheetTO = gridAttendanceSheet.selectedItem as AttendanceSheetTO;
	if(attSheet.status == "Iniciado"){
		
		WindowsMessage.question("Tem certeza que deseja finalizar o atendimento? ","Finalizar",function (event:CloseEvent):void{
			if(event.detail == Alert.YES){
				attSheet.status = "Finalizado";
				attendanceSheetRemote.update(attSheet);
				findBookingByStatusController();
				gridAttendanceDetail.dataProvider = null;
			}
		});
	}else{
		WindowsMessage.alarm("O atendimento do cliente "+attSheet.customer.person.name 	 +
			" deve estar INICIADO para ser finalizado!");
	}
}
private function cancelAttendance():void{
	var attSheet:AttendanceSheetTO = gridAttendanceSheet.selectedItem as AttendanceSheetTO;
	
	if(attSheet.status != "Finalizado" && attSheet.status != "Cancelado"){
		
		WindowsMessage.question("Tem certeza que deseja cancelar o atendimento? ","Finalizar",function (event:CloseEvent):void{
			if(event.detail == Alert.YES){
				attSheet.status = "Cancelado";
				cancelAttendanceSheetRemote.update(attSheet);
				findBookingByStatusController();
				gridAttendanceDetail.dataProvider = null;
			}
		});
	}else{
		WindowsMessage.alarm("O atendimento do cliente "+attSheet.customer.person.name 	 +
			" nÃ£o pode ser cancelado depois de ter sido Finalizado/Cancelado!");
	}
}
private function showAlterAttendanceSheet():void{
	
}
private function getCbStatus():void{
	
	listStatus.addItem("Reserva");
	listStatus.addItem("Iniciado");
	listStatus.addItem("Finalizado");
	//listStatus.addItem("Cancelado");
	
}	

private function newAttendance():void{
	this.currentState = "bookingView";
}

private function findBusyEmployeeForDate():void{
	//busyAttendanceSheet.date = new Date(dateField.selectedDate.fullYear, dateField.selectedDate.month, dateField.selectedDate.date, null, null, null, null);
	//Alert.show("Data: "+dateField.selectedDate);
	//Alert.show("entrou");
	gridAttendancesBusy.dataProvider = null;
	attendanceSheetRemote.findBusyEmployee(dateField.selectedDate);
	//Alert.show("chamou");
	//busyAttendanceSheet = gridBusyEmployee.selectedItem as AttendanceSheetTO;
	//gridAttendancesBusy.dataProvider = busyAttendanceSheet;
}

private function selectedBusyAttendance():void{
	busyAttendanceSheet = gridBusyEmployee.selectedItem as AttendanceSheetBusyTO;
	attendance = new ArrayCollection();
	for each(var att:AttendanceTO in busyAttendanceSheet.attendanceSheet.attendance){
		if(att.employee.person.name == busyAttendanceSheet.employee.person.name){
			att.employee = busyAttendanceSheet.employee;
			attendance.addItem(att);
		}
	}
	gridAttendancesBusy.dataProvider = attendance;
	//attendance = busyAttendanceSheet.attendanceSheet.attendance;
}

private function backSearch():void{
	
}